package com.laiketui.common.service.dubbo.plugin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.laiketui.common.mapper.*;
import com.laiketui.common.utils.tool.cache.RedisDataTool;
import com.laiketui.common.utils.tool.data.GoodsDataUtils;
import com.laiketui.domain.config.ConfiGureModel;
import com.laiketui.domain.lktconst.ErrorCode;
import com.laiketui.domain.order.OrderDataModel;
import com.laiketui.domain.order.OrderDetailsModel;
import com.laiketui.domain.order.OrderModel;
import com.laiketui.domain.plugin.auction.AuctionPromiseModel;
import com.laiketui.domain.plugin.jp.AuctionConfigModel;
import com.laiketui.domain.product.AuctionProductModel;
import com.laiketui.domain.product.ProductListModel;
import com.laiketui.domain.user.User;
import com.laiketui.domain.user.UserAddress;
import com.laiketui.domain.vo.plugin.auction.PromiseOrderVo;
import com.laiketui.common.api.PublicMemberService;
import com.laiketui.common.api.PublicOrderService;
import com.laiketui.common.api.PubliceService;
import com.laiketui.common.api.plugin.PubliceAuctionService;
import com.laiketui.core.cache.RedisUtil;
import com.laiketui.core.common.SplitUtils;
import com.laiketui.core.diyJavaFunction.StringUtils;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.lktconst.DictionaryConst;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.core.utils.tool.DataUtils;
import com.laiketui.core.utils.tool.DateUtil;
import com.laiketui.core.utils.tool.SerializePhpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

/**
 * 公共竞拍
 *
 * @author Trick
 * @date 2021/2/23 9:22
 */
@Service
public class PubliceAuctionServiceImpl implements PubliceAuctionService {
    private final Logger logger = LoggerFactory.getLogger(PubliceAuctionServiceImpl.class);

    @Autowired
    private AuctionProductModelMapper auctionProductModelMapper;

    @Autowired
    private ProductListModelMapper productListModelMapper;

    @Autowired
    private ConfiGureModelMapper confiGureModelMapper;

    @Autowired
    private AuctionConfigModelMapper auctionConfigModelMapper;

    @Autowired
    private AuctionPromiseModelMapper auctionPromiseModelMapper;

    @Autowired
    private OrderModelMapper orderModelMapper;

    @Autowired
    private OrderDetailsModelMapper orderDetailsModelMapper;

    @Autowired
    private PublicMemberService publicMemberService;

    @Autowired
    private PublicOrderService publicOrderService;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private UserBaseMapper userBaseMapper;

    @Autowired
    private PubliceService publiceService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private AuctionRecordModelMapper auctionRecordModelMapper;

    @Override
    public List<Map<String, Object>> getAuctionGoodsInfo(int storeId, User user, int pageStart, int pageEnd) throws LaiKeAPIException {
        List<Map<String, Object>> resultList = new ArrayList<>();
        try {
            if (user != null) {
                resultList = auctionProductModelMapper.selectUserAuctionGoodsInfo(storeId, user.getUser_id(), new Date(), pageStart, pageEnd);
            } else {
                resultList = auctionProductModelMapper.selectAuctionGoodsInfo(storeId, new Date(), pageStart, pageEnd);
            }
            for (Map<String, Object> map : resultList) {
                //获取图片
                String imgUrl = publiceService.getImgPath(map.get("imgurl").toString(), storeId);
                map.put("imgurl", imgUrl);
                map.put("status", "run");
                map.put("mark", 1);
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取正在竞拍商品信息 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getAuctionGoodsInfo");
        }
        return resultList;
    }

    @Override
    public List<Map<String, Object>> getAuctionRecordInfo(int storeId, int aid, int pageStart, int pageEnd) throws LaiKeAPIException {
        try {
            //获取该商品竞拍的最新三条竞拍信息
            Map<String, Object> parmaMap = new HashMap<>(16);
            parmaMap.put("store_id", storeId);
            parmaMap.put("auction_id", aid);
            parmaMap.put("pageStart", pageStart);
            parmaMap.put("pageEnd", pageEnd);
            parmaMap.put("id_sort", DataUtils.Sort.DESC.toString());
            parmaMap.put("add_time_sort", DataUtils.Sort.DESC.toString());
            parmaMap.put("price_sort", DataUtils.Sort.DESC.toString());
            List<Map<String, Object>> resBid = auctionRecordModelMapper.selectAuctionRecordList(parmaMap);
            for (Map<String, Object> map : resBid) {
                //处理手机号
                String phone = map.get("mobile") + "";
                if (!StringUtils.isEmpty(phone)) {
                    map.put("mobile", StringUtils.desensitizedPhoneNumber(phone));
                }
                map.put("user_name", map.get("user_name"));
                map.put("add_time", DateUtil.dateFormate(map.get("add_time") + "", GloabConst.TimePattern.YMDHMS));
            }
            return resBid;
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取正在砍价商品信息 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getAuctionRecordInfo");
        }
    }

    @Override
    public List<Map<String, Object>> indexRunning(int storeId, User user, int start, int end) {
        List<Map<String, Object>> resultList;
        try {
            Map<String, Object> parmaMap = new HashMap<>(16);
            parmaMap.put("store_id", storeId);
            parmaMap.put("invalid_systime", new Date());
            parmaMap.put("pageStart", start);
            parmaMap.put("pageEnd", end);
            parmaMap.put("group_id", "group by");
            parmaMap.put("id_sort", DataUtils.Sort.DESC.toString());
            String userId = "";
            if (user != null) {
                parmaMap.put("user_id", userId = user.getUser_id());
            }
            //1-进行中 2-已结束 3-已流拍
            List<Integer> statusList = new ArrayList<>();
            statusList.add(AuctionProductModel.Status.ONGOING);
            statusList.add(AuctionProductModel.Status.END);
            statusList.add(AuctionProductModel.Status.LOSE);
            parmaMap.put("statusList", statusList);

            resultList = auctionProductModelMapper.selectAuctionGoodsList(parmaMap);
            for (Map<String, Object> map : resultList) {
                //获取图片
                String imgUrl = publiceService.getImgPath(map.get("imgurl").toString(), storeId);
                map.put("imgurl", imgUrl);
                //竞拍商品状态
                int goodsStuats = Integer.parseInt(map.get("status").toString());
                //是否付款
                int ispay = Integer.parseInt(map.get("is_buy").toString());
                //订单编号
                String orderno = map.get("trade_no") + "";
                //获取最终成交人
                String successUserId = map.get("user_id") + "";
                if (StringUtils.isEmpty(successUserId)) {
                    successUserId = "";
                }
                //竞拍状态
                String status = "end";
                //竞拍活动标识 1-继续竞拍 2-已结束 3-未付款 4-我的订单 5-已流拍
                int mark = 1;
                if (goodsStuats == AuctionProductModel.Status.END) {
                    if (!successUserId.equals(userId)) {
                        mark = 2;
                    } else if (ispay == 0) {
                        mark = 3;
                        if (!StringUtils.isEmpty(orderno)) {
                            mark = 4;
                        }
                    }
                } else if (goodsStuats == AuctionProductModel.Status.LOSE) {
                    mark = 5;
                }
                if (goodsStuats == AuctionProductModel.Status.ONGOING) {
                    status = "run";
                }
                map.put("status", status);
                map.put("mark", mark);
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取正在竞拍商品信息 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "indexRunning");
        }
        return resultList;
    }

    @Override
    public List<Map<String, Object>> indexReady(int storeId, int start, int end) throws LaiKeAPIException {
        List<Map<String, Object>> resultList;
        try {
            resultList = auctionProductModelMapper.selectAuctionReadyGoodsInfo(storeId, start, end);
            for (Map<String, Object> map : resultList) {
                //获取图片
                String imgUrl = publiceService.getImgPath(map.get("imgurl").toString(), storeId);
                map.put("imgurl", imgUrl);
                map.put("mark", 0);
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取准备开始竞拍的商品信息 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "indexReady");
        }
        return resultList;
    }

    @Override
    public List<Map<String, Object>> indexMy(int storeId, User user, int start, int end) throws LaiKeAPIException {
        List<Map<String, Object>> resultList;
        try {
            if (user == null) {
                return new ArrayList<>();
            }
            Map<String, Object> parmaMap = new HashMap<>(16);
            parmaMap.put("store_id", storeId);
            parmaMap.put("invalid_systime", new Date());
            parmaMap.put("pageStart", start);
            parmaMap.put("pageEnd", end);
            parmaMap.put("group_id", "group by");
            parmaMap.put("id_sort", DataUtils.Sort.DESC.toString());
            String userId = "";
            parmaMap.put("user_id_my", userId = user.getUser_id());
            //1-进行中 2-已结束 3-已流拍
            List<Integer> statusList = new ArrayList<>();
            statusList.add(AuctionProductModel.Status.ONGOING);
            statusList.add(AuctionProductModel.Status.END);
            statusList.add(AuctionProductModel.Status.LOSE);
            parmaMap.put("statusList", statusList);

            resultList = auctionProductModelMapper.selectAuctionGoodsList(parmaMap);
            for (Map<String, Object> map : resultList) {
                //获取图片
                String imgUrl = publiceService.getImgPath(map.get("imgurl").toString(), storeId);
                map.put("imgurl", imgUrl);
                //竞拍商品状态
                int goodsStuats = Integer.parseInt(map.get("status").toString());
                //是否付款
                int ispay = Integer.parseInt(map.get("is_buy").toString());
                //订单编号
                String orderno = map.get("trade_no") + "";
                //获取最终成交人
                String successUserId = map.get("user_id") + "";
                if (StringUtils.isEmpty(successUserId)) {
                    successUserId = "";
                }
                //竞拍状态
                String status = "end";
                //竞拍活动标识 1-继续竞拍 2-已结束 3-未付款 4-我的订单 5-已流拍
                int mark = 1;
                if (goodsStuats == AuctionProductModel.Status.END) {
                    if (!successUserId.equals(userId)) {
                        mark = 2;
                    } else if (ispay == 0) {
                        mark = 3;
                        if (!StringUtils.isEmpty(orderno)) {
                            mark = 4;
                        }
                    }
                } else if (goodsStuats == AuctionProductModel.Status.LOSE) {
                    mark = 5;
                }
                if (goodsStuats == AuctionProductModel.Status.ONGOING) {
                    status = "run";
                }
                map.put("status", status);
                map.put("mark", mark);
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取我的竞拍商品信息 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "indexMy");
        }
        return resultList;
    }

    @Override
    public Map<String, Object> getAuctionDetail(int aid, User user, boolean isfx) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            //获取竞拍商品信息
            AuctionProductModel auctionProductModel = new AuctionProductModel();
            auctionProductModel.setId(aid);
            //分享照样显示出竞拍商品
            if (!isfx) {
                auctionProductModel.setIs_show(1);
                auctionProductModel.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS);
            }
            auctionProductModel = auctionProductModelMapper.selectOne(auctionProductModel);
            if (auctionProductModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_JPSPBCZ, "竞拍商品不存在");
            }
            Map<String, Object> auctionGoodsMap = JSON.parseObject(JSON.toJSONString(auctionProductModel), new TypeReference<Map<String, Object>>() {
            });
            Integer mark = auctionProductModel.getStatus();
            int type = mark;
            switch (mark) {
                case AuctionProductModel.Status.END:
                    mark = 2;
                    break;
                case AuctionProductModel.Status.LOSE:
                    mark = 5;
                    break;
                default:
                    break;
            }
            resultMap.put("type", type);
            auctionGoodsMap.put("mark", mark);
            auctionGoodsMap.put("imgurl", publiceService.getImgPath(auctionProductModel.getImgurl(), auctionProductModel.getStore_id()));
            auctionGoodsMap.put("starttime", DateUtil.dateFormate(auctionProductModel.getStarttime(), GloabConst.TimePattern.YMDHMS));
            auctionGoodsMap.put("endtime", DateUtil.dateFormate(auctionProductModel.getEndtime(), GloabConst.TimePattern.YMDHMS));
            //计算离活动开始的秒数和活动结束的秒数
            long startSec = auctionProductModel.getStarttime().getTime() / 1000 - DateUtil.getTime();
            if (startSec < 0) {
                startSec = 0;
            }
            long endSec = auctionProductModel.getEndtime().getTime() / 1000 - DateUtil.getTime();
            if (endSec < 0) {
                endSec = 0;
            }
            auctionGoodsMap.put("start_second", startSec);
            auctionGoodsMap.put("end_second", endSec);

            //出价等待时间
            long nextWaitTime = 0;
            if (user != null) {
                //是否交了押金
                AuctionPromiseModel auctionPromiseModel = new AuctionPromiseModel();
                auctionPromiseModel.setStore_id(auctionProductModel.getStore_id());
                auctionPromiseModel.setUser_id(user.getUser_id());
                auctionPromiseModel.setIs_pay(1);
                int count = auctionProductModelMapper.selectCount(auctionProductModel);
                int isbzj = count > 0 ? 1 : 0;
                //如果登录了则查询上一次可加价时间,计算下次加价时间
                String time = auctionRecordModelMapper.selectAuctionTime(auctionProductModel.getStore_id(), auctionProductModel.getId(), user.getUser_id());
                if (!StringUtils.isEmpty(time)) {
                    AuctionConfigModel auctionConfigModel = new AuctionConfigModel();
                    auctionConfigModel.setStore_id(auctionProductModel.getStore_id());
                    auctionConfigModel = auctionConfigModelMapper.selectOne(auctionConfigModel);
                    if (auctionConfigModel != null) {
                        //加价缓冲时间
                        int waitTime = auctionConfigModel.getWait_time();
                        Date timeDate = DateUtil.dateFormateToDate(time, GloabConst.TimePattern.YMDHMS);
                        //计算下次加价时间
                        Date nextDate = DateUtil.getAddDateBySecond(timeDate, waitTime);
                        if (DateUtil.dateCompare(nextDate, new Date())) {
                            nextWaitTime = nextDate.getTime() / 1000 - DateUtil.getTime();
                        }
                    }
                }
                //刷新缓存
                user = userBaseMapper.selectByPrimaryKey(user.getId());
                RedisDataTool.refreshRedisUserCache(user.getAccess_id(), user, redisUtil);
                resultMap.put("money", user.getMoney());
                //是否交了押金
                resultMap.put("is_promise", isbzj);
                //是否设置了支付密码
                resultMap.put("password_status", StringUtils.isEmpty(user.getPassword()) ? 0 : 1);
            } else {
                //未登录,获取该商品的最终得主
                AuctionProductModel auctionProduct = new AuctionProductModel();
                auctionProduct.setId(auctionProductModel.getId());
                auctionProduct.setStatus(AuctionProductModel.Status.END);
                auctionProduct = auctionProductModelMapper.selectOne(auctionProduct);
                if (auctionProduct != null) {
                    resultMap.put("is_promise", auctionProduct.getUser_id());
                }
            }
            auctionGoodsMap.put("wait_time", nextWaitTime);

            //竞拍商品参数处理
            Map<String, Integer> goodsIdMap = this.getGoods(auctionProductModel.getAttribute());
            //获取商品id,规格id
            Integer pid = goodsIdMap.get("goodsId"), attrId = goodsIdMap.get("attrId");
            auctionGoodsMap.put("product_id", pid);
            //获取商品详情信息
            String content = "";
            ProductListModel productListModel = productListModelMapper.selectByPrimaryKey(pid);
            if (productListModel != null) {
                content = productListModel.getContent();
            }
            auctionGoodsMap.put("content", content);
            //获取规格信息
            String attr = "";
            ConfiGureModel confiGureModel = confiGureModelMapper.selectByPrimaryKey(attrId);
            if (confiGureModel != null) {
                attr = GoodsDataUtils.getProductSkuValue(confiGureModel.getAttribute());
            }
            auctionGoodsMap.put("attr", attr);

            List<Map<String, Object>> resList = new ArrayList<>();
            resList.add(auctionGoodsMap);
            resultMap.put("res", resList);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取竞拍商品明细 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getAuctionDetail");
        }
        return resultMap;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String createOrder(int storeId, Integer storeType, int aid, String userId, String payType) throws LaiKeAPIException {
        String orderno;
        try {
            //生成订单号
            orderno = publicOrderService.createOrderNo(DictionaryConst.OrdersType.ORDERS_HEADER_JP);
            //获取活动商品信息
            AuctionProductModel auctionProductModel = auctionProductModelMapper.selectByPrimaryKey(aid);
            if (auctionProductModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_JPSPBCZ, "竞拍商品不存在");
            }
            if (!StringUtils.isEmpty(auctionProductModel.getTrade_no())) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_NYSCDFKDDQQWZF, "您已生成待付款订单，请前往支付！");
            }
            //生成支付订单号
            String serialno = publicOrderService.createOrderNo(DictionaryConst.OrdersType.ORDERS_HEADER_JP);
            //获取保证金信息
            AuctionPromiseModel auctionPromiseModel = new AuctionPromiseModel();
            auctionPromiseModel.setStore_id(storeId);
            auctionPromiseModel.setUser_id(userId);
            auctionPromiseModel = auctionPromiseModelMapper.selectOne(auctionPromiseModel);
            if (auctionPromiseModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WJBZJ, "未交保证金");
            }

            //竞拍商品参数处理
            Map<String, Integer> goodsIdMap = this.getGoods(auctionProductModel.getAttribute());
            //获取商品id,规格id
            Integer pid = goodsIdMap.get("goodsId"), attrId = goodsIdMap.get("attrId");
            ProductListModel productListModel = productListModelMapper.selectByPrimaryKey(pid);
            ConfiGureModel confiGureModel = confiGureModelMapper.selectByPrimaryKey(attrId);
            if (confiGureModel == null || productListModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SJYC, "数据异常");
            }
            //运费id
            Integer yunfeiId = StringUtils.stringParseInt(productListModel.getFreight());
            //获取运费
            UserAddress userAddress = userAddressMapper.selectByPrimaryKey(auctionPromiseModel.getAddress_id());
            BigDecimal freightPrice = publicOrderService.getFreight(yunfeiId, userAddress);
            if (freightPrice == null) {
                freightPrice = new BigDecimal("0");
            }

            //生成订单明细
            OrderDetailsModel orderDetailsSave = new OrderDetailsModel();
            orderDetailsSave.setStore_id(storeId);
            orderDetailsSave.setUser_id(userId);
            orderDetailsSave.setP_id(pid);
            orderDetailsSave.setP_name(productListModel.getProduct_title());
            orderDetailsSave.setP_price(confiGureModel.getPrice());
            orderDetailsSave.setNum(1);
            orderDetailsSave.setUnit(confiGureModel.getUnit());
            orderDetailsSave.setR_sNo(orderno);
            orderDetailsSave.setR_status(DictionaryConst.OrdersStatus.ORDERS_R_STATUS_UNPAID);
            orderDetailsSave.setSid(confiGureModel.getId() + "");
            orderDetailsSave.setFreight(freightPrice);
            orderDetailsSave.setAdd_time(new Date());
            orderDetailsSave.setSize(GoodsDataUtils.getProductSkuValue(confiGureModel.getAttribute()));
            int row = orderDetailsModelMapper.insertSelective(orderDetailsSave);
            if (row < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XDSB, "下单失败");
            }
            row = productListModelMapper.reduceGoodsStockNum(productListModel.getId(), 1);
            if (row < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPKCBZ, "商品库存不足");
            }
            //扣减库存
            row = confiGureModelMapper.reduceGoodsStockNum(-1, confiGureModel.getId());
            if (row < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPKCBZ, "商品库存不足");
            }
            //订单总价
            BigDecimal orderPrice = new BigDecimal("0");
            //计算会员特惠
            BigDecimal userRate = new BigDecimal(publicMemberService.getMemberGradeRate(DictionaryConst.OrdersType.ORDERS_HEADER_JP, userId, storeId) + "");
            //计算订单总价
            orderPrice = orderPrice.add(auctionProductModel.getCurrent_price()).multiply(userRate).add(freightPrice);
            if (orderPrice.compareTo(new BigDecimal(BigInteger.ZERO)) <= 0) {
                logger.debug("订单金额{} 折扣：{} 竞拍活动id为{}", orderPrice, orderPrice, aid);
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XDSB, "下单失败");
            }
            //生成订单信息
            OrderModel orderSave = new OrderModel();
            orderSave.setStore_id(storeId);
            orderSave.setUser_id(userId);
            orderSave.setName(userAddress.getName());
            orderSave.setMobile(userAddress.getTel());
            orderSave.setNum(orderDetailsSave.getNum());
            orderSave.setZ_price(orderPrice);
            orderSave.setsNo(orderno);
            orderSave.setSheng(userAddress.getSheng());
            orderSave.setShi(userAddress.getCity());
            orderSave.setXian(userAddress.getQuyu());
            orderSave.setAddress(userAddress.getAddress());
            orderSave.setRemark(" ");
            orderSave.setPay(payType);
            orderSave.setStatus(DictionaryConst.OrdersStatus.ORDERS_R_STATUS_UNPAID);
            orderSave.setCoupon_id("0");
            orderSave.setConsumer_money(0);
            orderSave.setSpz_price(auctionProductModel.getCurrent_price());
            orderSave.setSource(storeType);
            orderSave.setOtype(DictionaryConst.OrdersType.ORDERS_HEADER_JP);
            orderSave.setMch_id(SplitUtils.DH + auctionProductModel.getMch_id() + SplitUtils.DH);
            orderSave.setReal_sno(serialno);
            orderSave.setGrade_rate(userRate);
            orderSave.setZ_price(orderPrice);
            orderSave.setSubtraction_id(0);
            orderSave.setAdd_time(new Date());
            row = orderModelMapper.insertSelective(orderSave);
            if (row < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XDSB, "下单失败");
            }
            //修改竞拍商品订单号
            row = auctionProductModelMapper.updateAuctionOrder(orderno, 0, storeId, aid, userId);
            if (row < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XDSB, "下单失败");
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("竞拍下单 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "createOrder");
        }
        return orderno;
    }

    @Override
    public void paymentPromise(PromiseOrderVo vo, String orderNo) throws LaiKeAPIException {
        try {
            int row;
            row = auctionPromiseModelMapper.updateStatus(vo.getStoreId(), orderNo, OrderDataModel.PayStatus.PAYMENT);
            if (row < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_ZFSB, "支付失败");
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("竞拍保证金支付回调 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "paymentPromise");
        }
    }

    /**
     * 获取竞拍商品明细
     *
     * @param attribute -
     * @return Map
     * @author Trick
     * @date 2021/4/24 11:18
     */
    private Map<String, Integer> getGoods(String attribute) {
        Map<String, Integer> resultMap = new HashMap<>(16);
        try {
            //获取商品信息
            Map<Integer, Map<Integer, Object>> attributeMap = SerializePhpUtils.getAuctionProductAttribute(attribute);
            //获取商品id,规格id
            Integer pid = null, attrId = null;
            if (attributeMap != null) {
                for (Integer goodsId : attributeMap.keySet()) {
                    pid = goodsId;
                    Map<Integer, Object> attrMap = attributeMap.get(goodsId);
                    for (Integer id : attrMap.keySet()) {
                        attrId = id;
                        break;
                    }
                }
            }
            resultMap.put("goodsId", pid);
            resultMap.put("attrId", attrId);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取竞拍商品明细 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getGoods");
        }
        return resultMap;
    }
}

